package com.hefan.api.aop;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.api.util.Constants;
import com.hefan.api.util.sensitive.SensitivewordFilter;
import com.hefan.common.util.HttpUtils;


public class SensitiveIntercepor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(SensitiveIntercepor.class);

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		try {
			ResultBean res = new ResultBean();
			response.setCharacterEncoding(Constants.HTTP_CHARSET);
			response.setContentType(Constants.HTTP_JSON);
			PrintWriter out = null;
			String data = HttpUtils.getParam(request, "data", "");
			if(StringUtils.isNotBlank(data)){
				SensitivewordFilter filter = new SensitivewordFilter();
				boolean hs = filter.isContaintSensitiveWord(data, 1);
				if(hs){
					out = response.getWriter();
					res.setCode(ResultCode.HasSensitiveWord.get_code());
					res.setMsg(ResultCode.HasSensitiveWord.getMsg());
					res.setData("");
					out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) throws Exception {
    }

}
